<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-15 10:26:31
 * @Last Modified time: 2023-02-16 14:36:17
 */
namespace app\console\services\store;

use frank\utils\helper\ArrayHelper;
use app\common\services\store\OrderService as CommonOrderService;
use app\common\enum\store\order\StatusEnum;
use app\common\enum\pay\PayStatusEnum;
use app\common\event\store\OrderEvent;
/**
 * 服务类：订单模块
 * Class OrderService
 * @package app\console\services\store
 */
class OrderService extends CommonOrderService
{
    /**
     * 未支付订单自动关闭
     */
    public function closeEvent( int $closeDays)
    {
        // 截止时间
        $deadlineTime =  $closeDays > 0?time() - ((int)$closeDays * 3600):-1;

        // 查询截止时间未支付的订单
        $list = $this->getListByClose($deadlineTime);
        // 订单ID集
        $orderIds = ArrayHelper::getArrayColumn($list, 'id');
        if (!empty($orderIds)) {
            foreach ($list as $order) {
            	
            	// 取消订单事件
                OrderEvent::cancel($order);

          //   	// 取消订单关闭支付单
          //       event('WechatPayClose',[
		        //     'order_no'=>$order['order_no']
		        // ]);
		    }
            // 批量更新订单状态为已取消
            $this->onBatchUpdate($orderIds, ['order_status' => StatusEnum::INVALID]);
        }

        return count($orderIds);

        // 记录日志
        // Tools::taskLogs('Order', 'closeEvent', [
        //     'closeDays' => $closeDays,
        //     'deadlineTime' => $deadlineTime,
        //     'orderIds' => helper::jsonEncode($orderIds)
        // ]);
    }

     /**
     * 查询截止时间未支付的订单列表
     */
    public function getListByClose( int $deadlineTime)
    {
        // 查询条件
        $filter['pay_status'] = PayStatusEnum::PENDING;
        $filter['order_status'] = StatusEnum::AFOOT;
        // 查询列表记录
        return $this->dao->search($filter)->where('create_time', '<=', $deadlineTime)
            ->select();
    }
}